<template>
  <div>
    <a-spin :spinning="loading">
      <a-card :bordered="false" :bodyStyle="{ padding: '24px 16px', height: '100%' }">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="8" :sm="24">
                <a-form-model-item label="搜索老师：">
                  <a-input
                    v-model="keywords"
                    placeholder="请输入教师姓名/手机号(回车搜索)"
                    @pressEnter="$refs.table.refresh(true)"
                  >
                    <a-tooltip slot="suffix" title="请输入教师姓名/手机号">
                      <a-icon
                        type="search"
                        style="color: rgba(0,0,0,.45)"
                        @click="$refs.table.refresh(true)"
                      />
                    </a-tooltip>
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-model-item label="授课科目：">
                  <a-select v-model="queryParam.subject_id" allowClear placeholder="请选择授课科目">
                    <a-select-option
                      v-for="(item,index) in subjectList"
                      :key="index"
                      :value="item.id"
                    >{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- <div class="tableTopActionBtns">
        <a-button type="primary" class="searchBtn" @click="visibles = true">添加教师</a-button>
        </div>-->
        <s-table
          ref="table"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          class="user_management_table"
          :pagination="pagination"
        >
          <span slot="phone" slot-scope="text,record">
            <span style="margin-right:10px;">{{record.phone}}</span>
            <a-tooltip placement="rightTop">
              <template slot="title">
                <span v-if="record.wechat">已绑定微信</span>
                <span v-if="!record.wechat">未绑定微信</span>
              </template>
              <a-icon type="wechat" style="color:#52c41a" v-if="record.wechat" />
              <a-icon type="wechat" style="color:#ccc" v-if="!record.wechat" />
            </a-tooltip>
          </span>
          <span slot="already_on_hour" slot-scope="text,record">
            <a
              v-if="record.already_on_hour&&Number(record.already_on_hour)>0"
              @click="$router.push({ name: 'teacherInfo', query: { id: record.id } })"
            >{{+Number(record.already_on_hour)}}</a>
            <span v-else>-</span>
          </span>
          <span slot="name" slot-scope="text,record">
            <a
              @click="$router.push({ name: 'teacherInfo', query: { id: record.id } })"
            >{{record.name}}</a>
          </span>
          <span slot="is_enable" slot-scope="text,record">
            <a-switch :checked="text==1?true:false" @click="changeType(text,record)" />
          </span>
          <span slot="action" slot-scope="text,record">
            <a href="javascript:;" @click="edit(record.user_id)">编辑</a>
          </span>
        </s-table>

        <a-modal
          title="添加教师"
          :width="640"
          :visible="visibles"
          :confirmLoading="confirmLoading"
          @ok="modelSubmit('ruleForm')"
          @cancel="modelCancel"
          :destroyOnClose="true"
          :keyboard="false"
        >
          <a-spin :spinning="confirmLoading">
            <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" v-bind="layout">
              <a-form-model-item has-feedback label="姓名" prop="name">
                <a-input v-model="ruleForm.name" autocomplete="off" placeholder="请输入教师姓名" />
              </a-form-model-item>
              <a-form-model-item label="性别">
                <a-radio-group v-model="ruleForm.sex">
                  <a-radio :value="1">男</a-radio>
                  <a-radio :value="2">女</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <a-form-model-item label="手机号码">{{ruleForm.phone}}</a-form-model-item>
              <a-form-model-item label="擅长科目">
                <a-select
                  style="width:280px;"
                  v-model="ruleForm.subject_ids"
                  mode="multiple"
                  placeholder="请选择擅长科目"
                >
                  <a-select-option
                    v-for="(item,index) in subjectList"
                    :key="index"
                    :value="item.id"
                    v-if="item.is_enable==1"
                  >{{item.name}}</a-select-option>
                </a-select>
                <span style="color:blue;cursor:pointer;float:right; " @click="showChild">科目管理</span>
              </a-form-model-item>
              <a-form-model-item label="备注">
                <a-input v-model="ruleForm.remark" placeholder="请输入(选填,最多输入100个字符)" :max-length="100" autocomplete="off" />
              </a-form-model-item>
            </a-form-model>
          </a-spin>
        </a-modal>
        <user-info-model
          ref="editUser"
          @reload="$refs.table.refresh()"
          @closeLoading="loading=false"
          :type="1"
        ></user-info-model>
      </a-card>
    </a-spin>

    <upload-avatar ref="modal" @ok="setavatar" />
    <subject-model ref="subj_model" @reload="reloadSelect" />
  </div>
</template>
<script>
import { STable } from '@/components'
import uploadAvatar from '@/components/uploadAvatar'
import subjectModel from '@/components/subjectsModel'
import { accountEdit, roleList, accountInfo } from '@/api/account'
import { teacherList, teacherCreate, changeTeacherType, teacherEdit, havingClass } from '@/api/teacher'
import { subjectList } from '@/api/subject'
import { deepClone } from '@/utils/pub_methods_base'
import { campusList } from '@/api/structure'
import { changeUserInfo } from '@/api/login'
import userInfoModel from '@/components/editUserInfo'
export default {
  components: {
    STable,
    uploadAvatar,
    subjectModel,
    userInfoModel
  },
  created() {
    this.store_user = this.$store.state.user
    campusList({
      school_id: this.$store.state.user.school,
      type: 2
    }).then(res => {
      this.frameWorkList = res
    })
    roleList({
      school_id: this.$store.state.user.school,
      pageSize: 99999999999
    }).then(res => {
      this.rolesList = res.data
    })
    this.reloadSelect()
  },
  data() {
    return {
      loading: false,
      nowRouteTitle: '',
      store_user: null,
      keywords: '',
      queryParam: {
        subject_id: undefined,
        school_id: this.$store.state.user.school
      },
      pagination:{
        showTotal:total=>`共${total}条数据`,
      },  
      loadData: parameter => {
        return teacherList(Object.assign(parameter, this.queryParam, { keywords: this.keywords }))
          .then(res => {
            const result = res
            return result
          })
          .catch(err => {
            this.$message.error(err.data.message || '获取数据失败，请刷新页面或稍后再试')
          })
      },
      columns: [
        {
          title: '教师姓名',
          dataIndex: 'name',
          width: 120,
          fixed: 'left',
          ellipsis: true,
          align: 'left',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '性别',
          dataIndex: 'sex',
          align: 'center',
          ellipsis: true,
          customRender(sex) {
            return sex == 1 ? '男' : sex == 2 ? '女' : '' //1是男，2是女
          }
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          ellipsis: true,
          scopedSlots: { customRender: 'phone' }
        },
        {
          title: '科目',
          dataIndex: 'subject_names',
          ellipsis: true,
          align: 'center'
          //  scopedSlots: { customRender: 'actions' },
        },

        {
          title: '上月课时',
          dataIndex: 'last_month_hour',
          ellipsis: true,
          align: 'center',
          customRender(text) {
            return +Number(text)>0?+Number(text):'-'
          }
        },
        {
          title: '本月课时',
          dataIndex: 'this_month_hour',
          ellipsis: true,
          align: 'center',
          customRender(text) {
            return +Number(text)>0?+Number(text):'-'
          }
        },
        {
          title: '已上课时',
          dataIndex: 'already_on_hour',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'already_on_hour' }
        },

        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          width: 100,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      //添加教师
      confirmLoading: false,
      visibles: false,
      ruleForm: {
        name: '',
        sex: 1,
        phone: '',
        remarks: '',
        subject_ids: []
      },
      rules: {
        name: [{ required: true, message: '请输入教师姓名' }]
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 }
      },
      option: {
        img: '',
        info: true,
        size: 1,
        outputType: 'jpeg',
        canScale: false,
        autoCrop: true,
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 180,
        autoCropHeight: 180,
        fixedBox: true,
        // 开启宽度和高度比例
        fixed: true,
        fixedNumber: [1, 1]
      },
      subjectList: [],
      frameWorkList: [],
      rolesList: [],
      mdl: {},
      editVisibles: false
    }
  },
  methods: {
    setavatar(url) {
      //上传图片
      this.option.img = url
      this.ruleForm.head_portrait = url
    },
    modelSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = deepClone(this.ruleForm)
          data.school_id = this.store_user.school
          teacherCreate(data)
            .then(res => {
              this.$message.success('添加成功')
              this.confirmLoading = false
              this.ruleForm = {
                head_portrait: '',
                name: '',
                sex: 1,
                phone: '',
                remarks: '',
                subject_ids: []
              }
              this.visibles = false
              this.$refs.table.refresh()
            })
            .catch(err => {
              this.$message.error(err.data.message || '添加失败')
            })
        } else {
          return false
        }
      })
    },
    changeType(data, e) {
      // console.log(data)
      // 关闭是2
      if (data == 2 || data == null) {
        changeTeacherType({ is_enable: 1 }, e.id)
          .then(res => {
            this.$refs.table.refresh(false)
          })
          .catch(err => {
            this.$message.error(err.data.message || '更新状态失败')
          })
      } else {
        let that = this
        this.$confirm({
          title: '提示',
          content: '确认禁用' + e.name + '？',
          okText: '确认',
          okType: 'primary',
          cancelText: '取消',
          onOk() {
            havingClass(e.id).then(res => {
              if (res.data.length < 1) {
                changeTeacherType({ is_enable: 2 }, e.id)
                  .then(res => {
                    that.$refs.table.refresh(false)
                  })
                  .catch(err => {
                    that.$message.error(err.data.message || '更新状态失败')
                  })
              } else {
                that.$confirm({
                  title: '警告：禁用老师' + e.name,
                  content: e.name + '还有班级未结业，是否确认把老师移出这些班级？',
                  okText: '确认移出并禁用',
                  okType: 'danger',
                  cancelText: '取消',
                  onOk() {
                    changeTeacherType({ is_enable: 2 }, e.id)
                      .then(res => {
                        that.$refs.table.refresh(false)
                      })
                      .catch(err => {
                        that.$message.error(err.data.message || '更新状态失败')
                      })
                  },
                  onCancel() {}
                })
              }
            })
          },
          onCancel() {
            console.log('Cancel')
          }
        })
      }
    },
    modelCancel() {
      this.visibles = false
      this.$refs.table.refresh()
    },
    clearSearch() {
      this.queryParam = {
        className: '',
        subjectName: '',
        teacherName: ''
      }
      ;(this.hiddenqueryParam = {
        classroom: '',
        isGradute: null,
        isArrang: null
      }),
        (this.queryParam_secondTab = {
          student: '',
          subjectName: '',
          teacherName: ''
        })
      this.hiddenqueryParam_secondTab = {
        classroom: '',
        isGradute: null,
        isArrang: null
      }
      this.$refs.table.refresh(true)
    },
    showChild() {
      this.$refs.subj_model.showModal()
    },
    reloadSelect() {
      subjectList({
        pageSize: 999999,
        school_id: this.$store.state.user.school
      })
        .then(res => {
          this.subjectList = res.data
        })
        .catch(error => {
          this.$message.error(err.data.message || '获取授课科目失败')
        })
    },
    edit(id) {
      this.loading = true
      accountInfo({ school_id: this.$store.state.user.school }, id)
        .then(res => {
          let record = new Object()
          this.mdl = Object.assign({}, res)
          record.id = this.mdl.id
          record.name = this.mdl.name
          record.sex = this.mdl.sex ? this.mdl.sex : 1
          record.phone = this.mdl.phone
          record.subject_ids = this.mdl.subject_id
          record.structures_ids = this.mdl.department_ids
          record.role_ids = this.mdl.roleID
          record.remark = this.mdl.remark
          record.is_teaching = this.mdl.is_teaching
          this.$refs.editUser.showVisible(record)
        })
        .catch(err => {
          this.$message.error('获取教师详情失败')
        })
    }
  },
  watch: {
    'queryParam.keywords'() {
      this.$refs.table.refresh()
    },
    'queryParam.subject_id'() {
      this.$refs.table.refresh()
    },
    editVisibles(val) {
      if (val == false) {
        this.mdl = {}
        this.editForm = {}
      }
    }
  }
}
</script>

<style lang="less" scoped>
.searchBtn {
  margin: 16px 20px 16px 0;
}
.tableTopActionBtns {
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
  button {
    margin: 0 20px 16px 0;
  }
}
.myProjectTable > td {
  border-bottom: none !important;
}
.myProjectTable:nth-child(2n) {
  background: #fafafa;
}
.ant-upload-preview {
  position: relative;
  margin-left: 28px;
  width: 100%;
  max-width: 64px;
  margin-bottom: 20px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;

  .upload-icon {
    position: absolute;
    top: 0;
    right: 10px;
    font-size: 1rem;
    // padding: 0.5rem;
    background: rgba(222, 221, 221, 0.7);
    border-radius: 50%;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }
  .mask {
    opacity: 0;
    position: absolute;
    background: rgba(0, 0, 0, 0.4);
    cursor: pointer;
    transition: opacity 0.4s;

    &:hover {
      opacity: 1;
    }

    i {
      font-size: 1rem;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -0.5rem;
      margin-top: -0.5rem;
      color: #d6d6d6;
    }
  }

  img,
  .mask {
    width: 100%;
    max-width: 64px;
    height: 64px;
    border-radius: 50%;
    overflow: hidden;
  }
}
</style>